package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.service.ShoppingCartService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.ws.WebSocket;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import springfox.documentation.spring.web.json.Json;

import javax.annotation.Resource;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.*;
import java.util.concurrent.CancellationException;
import java.util.concurrent.RejectedExecutionException;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImp implements OrderService {
    @Resource
    OrderMapper ordermapper;
    @Resource
    AddressBookMapper addressBookMapper;
    @Resource
    ShoppingCartMapper shoppingCartMapper;

    @Resource
    OrderDetailMapper orderDetailMapper;

    @Resource
    UserMapper userMapper;

    @Resource
    OrderMapper orderMapper;
    @Resource
    ShoppingCartService shoppingCartService;


    @Resource
    private WeChatPayUtil weChatPayUtil;

    @Resource
    WebSocket webSocket;

    @Override
    public OrderVO getOrderDetail(Long id) {
        List<OrderDetail> detailsByOderId = orderDetailMapper.getDetailsByOderId(id);
        Orders orders = orderMapper.getById(id);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(detailsByOderId);
        return orderVO;
    }

    @Override
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO submitDTO) {

        //处理异常
        AddressBook addressBook = addressBookMapper.getById(submitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.selectByUserId(BaseContext.getCurrentId());
        if (shoppingCarts == null || shoppingCarts.isEmpty()) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //向订单表插入树
        Orders orders = new Orders();
        BeanUtils.copyProperties(submitDTO, orders);

        orders.setOrderTime(LocalDateTime.now());
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setPayStatus(Orders.UN_PAID);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setUserId(BaseContext.getCurrentId());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        String address = addressBook.getProvinceName() + addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail();
        orders.setAddress(address);
        ordermapper.insert(orders);
        List<OrderDetail> orderDetails = new ArrayList<>();
        //向明细表插入数据

        for (ShoppingCart shoppingCart : shoppingCarts) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetails.add(orderDetail);
        }
        orderDetailMapper.insertBatch(orderDetails);
        //清空购物车
        shoppingCartMapper.deleteByUserId(BaseContext.getCurrentId());
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder().orderTime(orders.getOrderTime()).id(orders.getId()).orderAmount(orders.getAmount()).orderNumber(orders.getNumber()).build();
        //下面注释的代码
        /*Thread thread = new Thread(()->{
            try {
                Thread.sleep(70000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            Orders orders1 = orderMapper.getById(orders.getId());
            LocalDateTime orderTime = orders1.getOrderTime();
            long epochMilli = orderTime.toInstant(ZoneOffset.of("+8")).toEpochMilli();
            long epochMilli1 = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
            long l = epochMilli1 - epochMilli;
            if(l>60000){
                Orders orders2 = new Orders();
                orders2.setId(orders1.getId());
                orders2.setStatus(Orders.CANCELLED);
                orderMapper.update(orders2);
                log.info("订单超时已自动取消");
            }

        });
        thread.start();*/
        return orderSubmitVO;
    }


    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        /**
         * 调用微信支付接口，生成预支付交易单
         *         JSONObject jsonObject = weChatPayUtil.pay(
         *         ordersPaymentDTO.getOrderNumber(), //商户订单号
         *         new BigDecimal(0.01), //支付金额，单位 元
         *         "苍穹外卖订单", //商品描述
         *          user.getOpenid() //微信用户的openid
         *  );
         *  if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
         *      throw new OrderBusinessException("该订单已支付");
         }*/

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", "ORDERPAID");
        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        // 以下步骤为了跳过微信支付
        //直接修改订单表使其为已经支付的状态
        paySuccess(ordersPaymentDTO.getOrderNumber());
        return vo;
    }

    @Override
    public void reminder(Long id) {
        HashMap<String, Object> hash = new HashMap<>();
        hash.put("type", 2);
        hash.put("orderId", id);
        Orders db = orderMapper.getById(id);
        hash.put("content", "订单号: " + db.getNumber());
        webSocket.sendAll(JSON.toJSONString(hash));
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder().id(ordersDB.getId()).status(Orders.TO_BE_CONFIRMED).payStatus(Orders.PAID).checkoutTime(LocalDateTime.now()).build();

        orderMapper.update(orders);

        //像前端推送来单消息
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("type", 1);
        hashMap.put("orderId", ordersDB.getId());
        hashMap.put("content", ordersDB.getNumber());
        ObjectMapper objectMapper = new ObjectMapper();
        String msg = "";
        try {
            msg = objectMapper.writeValueAsString(hashMap);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        webSocket.sendAll(msg);
    }

    @Override
    public PageResult page(int page, int pageSize, int status) {
        PageHelper.startPage(page, pageSize);
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(status);
        Page<Orders> pages = ordermapper.page(ordersPageQueryDTO);
        List<Orders> result = pages.getResult();
        List<OrderVO> orderVOS = new ArrayList<>();
        for (Orders orders : result) {
            Long id = orders.getId();
            List<OrderDetail> orderDetails = orderDetailMapper.getDetailsByOderId(id);
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(orders, orderVO);
            orderVO.setOrderDetailList(orderDetails);
            orderVOS.add(orderVO);
        }
        PageResult pageResult = new PageResult(pages.getTotal(), orderVOS);
        return pageResult;
    }

    @Override
    public PageResult page(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        Page<Orders> pages = ordermapper.page(ordersPageQueryDTO);
        List<Orders> result = pages.getResult();
        List<OrderVO> orderVOS = new ArrayList<>();
        for (Orders orders : result) {
            Long id = orders.getId();
            List<OrderDetail> orderDetails = orderDetailMapper.getDetailsByOderId(id);
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(orders, orderVO);
            orderVO.setOrderDetailList(orderDetails);
            orderVOS.add(orderVO);
        }
        PageResult pageResult = new PageResult(pages.getTotal(), orderVOS);
        return pageResult;
    }

    @Override
    public void cancel(Long id) {
        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(Orders.CANCELLED);
        ordermapper.update(orders);
    }

    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        //获取订单
        Orders orders = orderMapper.getById(ordersCancelDTO.getId());
        if (orders == null) {
            throw new CancellationException("订单号有误");
        }

        //判断是否付款
        if (orders.getPayStatus().equals(Orders.PAID)) {
            log.info("正在退款");
        }
        //修改订单状态
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());
        orders.setStatus(Orders.CANCELLED);
        orderMapper.update(orders);
    }

    @Override
    public void orderAgain(Long id) {

        List<OrderDetail> detailsByOderId = orderDetailMapper.getDetailsByOderId(id);

        for (OrderDetail detail : detailsByOderId) {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(detail, shoppingCart);
            shoppingCart.setId(null);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCart.setUserId(BaseContext.getCurrentId());
            List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);
            if (list != null && !list.isEmpty()) {
                shoppingCart.setNumber(shoppingCart.getNumber() + 1);
                shoppingCartMapper.updateById(shoppingCart);
            } else {
                shoppingCartMapper.insert(shoppingCart);
            }

        }

    }

    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        //根据条件查询订单
        Page<Orders> page = orderMapper.page(ordersPageQueryDTO);
        //我们需要orderVO,来封装菜品详情
        List<OrderVO> orderVOList = getOrderVOList(page);

        return new PageResult(page.getTotal(), orderVOList);
    }

    @Override
    public OrderStatisticsVO statistics() {
        //查询待接单数量
        Integer count1 = ordermapper.getBystatus(2);
        //查询带派送的数量
        Integer count2 = ordermapper.getBystatus(3);
        //查询派送中的数量
        Integer count3 = ordermapper.getBystatus(4);
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(count1);
        orderStatisticsVO.setConfirmed(count2);
        orderStatisticsVO.setDeliveryInProgress(count3);
        return orderStatisticsVO;
    }

    @Override
    public void confirm(OrdersConfirmDTO confirmDTO) {
        Orders orders = Orders.builder()
                .id(confirmDTO.getId())
                .status(Orders.CONFIRMED)
                .build();

        ordermapper.update(orders);
    }

    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        Orders orders = ordermapper.getById(ordersRejectionDTO.getId());
        //判断能否拒单
        if (!orders.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new RejectedExecutionException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //判断用户是否付款
        if (orders.getPayStatus().equals(Orders.PAID)) {
            log.info("正在退款");
        }
        //修改订单状态
        orders.setCancelTime(LocalDateTime.now());
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orders.setStatus(Orders.CANCELLED);
        orderMapper.update(orders);
    }

    @Override
    public void delivery(Long id) {
        Orders ordersDB = orderMapper.getById(id);
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.update(orders);
    }

    @Override
    public void complete(Long id) {
        Orders orderDB = orderMapper.getById(id);
        if (orderDB == null || !orderDB.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = new Orders();
        orders.setId(orderDB.getId());
        orders.setStatus(Orders.COMPLETED);
        orders.setDeliveryTime(LocalDateTime.now());
        orderMapper.update(orders);

    }

    private List<OrderVO> getOrderVOList(Page<Orders> page) {
        List<OrderVO> list = new ArrayList<>();
        if (page != null && !page.getResult().isEmpty()) {
            for (Orders order : page.getResult()) {
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(order, orderVO);
                orderVO.setOrderDishes(getOrderDishesStr(order));
                list.add(orderVO);
            }
        }
        return list;
    }

    /**
     * 根据订单id获取菜品信息字符串
     *
     * @param orders
     * @return
     */
    private String getOrderDishesStr(Orders orders) {
        List<OrderDetail> orderDetailList = orderDetailMapper.getDetailsByOderId(orders.getId());
        // 将每一条订单菜品信息拼接为字符串（格式：宫保鸡丁*3；）
        List<String> orderDishList = orderDetailList.stream().map(x -> {
            String orderDish = x.getName() + "*" + x.getNumber() + ";";
            return orderDish;
        }).collect(Collectors.toList());

        // 将该订单对应的所有菜品信息拼接在一起
        return String.join("", orderDishList);
    }
}
